package com.example.knowledge.image.photo;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.knowledge.R;
import com.fifedu.lib_common_utils.CommonUtils;
import com.fifedu.lib_common_utils.FileUtils;
import com.fifedu.lib_common_utils.dialog.BaseDialogUtils;
import com.fifedu.lib_common_utils.dialog.SelectItemCallBack;
import com.fifedu.lib_common_utils.dialog.SelectItems;
import com.fifedu.lib_common_utils.permission.PermissionCallBack;
import com.fifedu.lib_common_utils.permission.PermissionUtils;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class PhotoSelectActivity extends AppCompatActivity {
    private String TAG = "PhotoSelectActivity";
    public static final int SET_PIC_BY_CROP = 1000;
    public static final int SET_PIC_BY_CROP_RESUTL = 1003;
    private Bitmap bitMap; // 用来保存图片
    private static final int SET_PIC_BY_CAMERA = 1001;// 拍照获取照片
    private static final int SET_PIC_BY_ALBUM = 1002;// 从相册获取照片
    private ImageView ivCamera;
    private Uri destinationUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic_select);
        TextView tvSelectPic = findViewById(R.id.tv_select_pic);
        TextView tvCropPic = findViewById(R.id.tv_crop_pic);
        ivCamera = findViewById(R.id.iv_camera);
        tvCropPic.setOnClickListener(v -> {
            selectPhoto(SET_PIC_BY_CROP);
        });
        tvSelectPic.setOnClickListener(v -> {

            SelectItems selectItems = new SelectItems();
            List<SelectItems.SelectItem> list = new ArrayList<>();
            SelectItems.SelectItem selectItem = new SelectItems.SelectItem();
            selectItem.setText(getString(R.string.take_photo));
            selectItem.setTextColor(getResources().getColor(R.color.base_txt_blue));
            list.add(selectItem);
            SelectItems.SelectItem selectItem2 = new SelectItems.SelectItem();
            selectItem2.setText(getString(R.string.select_from_album));
            selectItem2.setTextColor(getResources().getColor(R.color.base_txt_blue));
            list.add(selectItem2);
            selectItems.setList(list);

            BaseDialogUtils.showSelectItemDialog(PhotoSelectActivity.this, selectItems, new SelectItemCallBack() {
                @Override
                public void onItemSelect(int position) {
                    if (position == 0) {
                        takePhoto();
                    } else if (position == 1) {
                        selectPhoto(SET_PIC_BY_ALBUM);
                    }
                }
            });
        });
    }

    //拍照获取图片
    protected void takePhoto() {
        PermissionUtils.requestPermissions(PhotoSelectActivity.this, false, new PermissionCallBack() {
            @Override
            public void onGranted() {
                try {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, SET_PIC_BY_CAMERA);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDeniedRational() {
                //勾选不在提示，且拒绝"
            }
        }, PermissionUtils.PERMISSION_CAMERA);

    }

    //从本地手机中选择图片
    private void selectPhoto(int code) {
        Intent localIntent = new Intent();
        localIntent.setType("image/*");
        localIntent.setAction("android.intent.action.GET_CONTENT");
        Intent localIntent2 = Intent.createChooser(localIntent, CommonUtils.getString(R.string.title_choosePic));
        startActivityForResult(localIntent2, code);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 获取到返回值时，弹框消失
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SET_PIC_BY_ALBUM: // 从本地选择图片
                if (bitMap != null && !bitMap.isRecycled()) {
                    bitMap.recycle();
                }
                if (data != null) {
                    Uri selectedImageUri = data.getData();
                    if (selectedImageUri != null) {
                        try {
                            bitMap = BitmapFactory.decodeStream(getContentResolver()
                                    .openInputStream(selectedImageUri));

                        } catch (Exception e) {

                        }
                        final Bitmap teBitmap = bitMap;
                        ivCamera.setImageBitmap(teBitmap);
                    }
                }
                break;
            case SET_PIC_BY_CAMERA: // 拍照
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    if (bitMap != null && !bitMap.isRecycled()) {
                        bitMap.recycle();
                    }
                    if (bundle != null) {
                        bitMap = (Bitmap) bundle.get("data");
                        final Bitmap teBitmap = bitMap;
                        ivCamera.setImageBitmap(teBitmap);
                    }
                }
                break;
            case SET_PIC_BY_CROP:
                File pictureFile = new File(FileUtils.getPhotosExternalCacheDir(), Calendar.getInstance().getTimeInMillis() + ".jpg");
                destinationUri = FileUtils.getFileUri(pictureFile);
                Uri sourceUri = data.getData();
                UCrop.of(sourceUri, destinationUri)
                        .withAspectRatio(1, 1)
                        .start(this, SET_PIC_BY_CROP_RESUTL);
                break;
            case SET_PIC_BY_CROP_RESUTL:
                ivCamera.setImageURI(destinationUri);
                break;
        }
    }

}
